﻿module Sustainalytics.EsgRatings {
    export class ReferenceUniversesService implements IReferenceUniversesService {
        private $q: ng.IQService;
        private $http: ng.IHttpService;
        private notificationFactory: INotificationFactory;
        private staticObjects: IStaticObjects;
        private $location: ng.ILocationService;
        private $upload: any;

        constructor($q: ng.IQService, $http: ng.IHttpService, $location: ng.ILocationService, notificationFactory: INotificationFactory, staticObjects: IStaticObjects, $upload) {
            this.$q = $q;
            this.$http = $http;
            this.notificationFactory = notificationFactory;
            this.staticObjects = staticObjects;
            this.$location = $location;
            this.$upload = $upload;
        }

        public getReferenceUniverses(): ng.IPromise<Array<IReferenceUniverse>> {
            var ctx = this;
            var def = ctx.$q.defer();

            var promise = ctx.$http.get(ctx.referenceUniverseFileUrl());
            promise
                .success(data => { def.resolve(data); })
                .error(err => { ctx.showError(err); def.reject(); });
            return def.promise;
        }

        public uploadReferenceUniverse(file: File, formData: any, progress: number): ng.IPromise<{}> {

            progress = 0;
            var ctx = this;
            var def = ctx.$q.defer();

            //var reader = new FileReader();
            //reader.onload = (data) => {
            //    return ctx.$upload.http({
            //        method: "POST",
            //        url: ctx.referenceUniverseFileUrl(),
            //        headers: { 'Content-Disposition': 'attachment; filename="' + file.name + '"', 'Content-Type': file.type, },
            //        data: reader.result
            //    })
            //        .progress(evt => { progress = (100.0 * evt.loaded / evt.total); })
            //        .success((data) => { def.resolve(data); });
            //};
            //reader.readAsArrayBuffer(file);
            ctx.$upload.upload({
                url: ctx.referenceUniverseFileUrl(), // webapi url
                method: "POST",
                data: { formData: formData},
                file: file
            })
                .progress(evt => { progress = (100.0 * evt.loaded / evt.total); })
                .success((data) => { def.resolve(data); })
                .error((data, status, headers, config) => {
                // file failed to upload
                    //def.resolve(data);
                console.log(data);
            });
            return def.promise;
        }
        private referenceUniverseFileUrl(): string {
            var ctx = this;
            return ctx.$location.protocol() + "://" + ctx.$location.host() + ":" + ctx.$location.port() +
                "/esgratingserv/api/v1/esgratings/referenceUniverses";
        }
        private showError(err) {
            var ctx = this;
            if (err && err['code'])
                ctx.notificationFactory.error('', ctx.staticObjects.getMessageByInternalCode(err['code']));
        }
    }

    // register service with Tools Angular module
    angular.module('Sustainalytics.EsgRatings').factory('ReferenceUniversesService',
        ($q: ng.IQService, $http: ng.IHttpService, $location: ng.ILocationService, notificationFactory: INotificationFactory, staticObjects: IStaticObjects, $upload) =>
            new ReferenceUniversesService($q, $http, $location, notificationFactory, staticObjects, $upload)
        );
}